package com.agent.spring.websocket;
import java.util.Map;

import javax.servlet.http.HttpSession;

import com.agent.shiro.ShiroUser;
import com.agent.spring.SpringConstants;
import com.agent.util.Constants;
import org.apache.shiro.SecurityUtils;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

/**
 * WebSocket拦截器
 * @author WANG
 *
 */
public class SpringWebSocketHandlerInterceptor extends HttpSessionHandshakeInterceptor {
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
                                   Map<String, Object> attributes) throws Exception {
        if (request instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
            HttpSession session = servletRequest.getServletRequest().getSession(false);
            ShiroUser user = (ShiroUser)SecurityUtils.getSubject().getPrincipal();
            if (user != null) {
                //使用userName区分WebSocketHandler，以便定向发送消息
                String userName = user.getUserName();
                if (userName==null) {
                    userName="default-id";
                }
                attributes.put(SpringConstants.WEBSOCKET_ID,userName+":"+session.getId());
            }
        }
        return super.beforeHandshake(request, response, wsHandler, attributes);

    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
                               Exception ex) {
        super.afterHandshake(request, response, wsHandler, ex);
    }
}